<template>
  <div class="hone">
    <!-- 商品轮播图 -->
    <div v-if="isLoading" class="loading-container">
      <!-- 使用 Vant Loading 组件 -->
      <van-loading type="spinner" size="24px" text="加载中..." color="#1e1e1e" />
    </div>

    <div v-if="items?.skuBarInfo?.list" class="carousel">
      <van-swipe v-model:active="activeIndex">
        <!-- 通过 v-model:active 双向绑定 activeIndex -->
        <van-swipe-item v-for="(item, index) in items.skuBarInfo.list" :key="index">
          <!-- 标签放到顶部 -->
          <p class="carousel-label">{{ item.label }}</p>
          <!-- 轮播图图片 -->
          <!-- <van-image :src="item.image" alt="first-frame" fit="cover" width="100%" /> -->
          <van-image 
            v-if="item.image"
            :src="item.image" 
            alt="first-frame" 
            fit="cover" 
            width="100%" 
            height="400px" 
            :lazy="true"  
          />
          <img v-else src="/images/zhanwei.jpg" alt="加载中" width="100%" height="400px" />
        </van-swipe-item>
      </van-swipe>

      <div class="lbdaoh">
        <div class="image-item"><img :src="items?.normalShareInfo?.imageUrl" alt="" /></div>
        <div class="lbdaoh2">
          <span>{{ items?.skuBarInfo?.labelV2 }}</span>
        </div>

        <div class="lbdaoh3">
          <div class="image-box">
            <!-- 点击小图片时更新 activeIndex -->
            <div
              v-for="(item, index) in items.skuBarInfo.list"
              :key="index"
              class="image-item"
              @click="setActiveIndex(index)"
              :class="{ active: activeIndex === index }"
            >
              <img :src="item.image" alt="轮播图图片" />
            </div>

          </div>
        </div>
      </div>
    </div>

    <div class="box2">
      <span>
        ￥
        <span class="b2span">{{ items?.itemInfo?.highNowPrice || '加载中...' }}</span>
      </span>
      <span class="box2-shop">已售 {{ items?.normalPrice?.sales || '加载中...' }}</span>
    </div>

    <div class="box3">
      <div class="b3span">
        {{ items?.normalShareInfo?.title || '加载中...' }}
      </div>
      <div>
        <div class="b3span2">帮我选</div>
      </div>
    </div>

    <div class="zwbox"></div>

    <div class="box4" @click="tiaozhuandd">
      <div>
        <span class="qianse">选择</span>
        <span>{{ items?.skuBarInfo?.labelV2 }}</span>
      </div>
      <div>></div>
    </div>

    <div>
      <div v-if="items?.itemServices?.columns" class="canshu">
        <div v-for="(service, index) in items.itemServices.columns" :key="index">
          <span>{{ service.desc }}</span>
        </div>
      </div>
      <p v-else>品质加载中...</p>
    </div>

    <div class="box4" @click="ycbox4 = !ycbox4">
      <div class="fuwu">
        <span class="qianse" style="display: flex; white-space: nowrap">服务</span>
        <div v-if="items?.shopInfo?.services" class="shop-services">
          <div v-for="(service, index) in items.shopInfo.services" :key="index">
            <span>{{ service.name }}</span>
          </div>
        </div>
        <p v-else>品质加载中...</p>
      </div>
      <div>></div>
    </div>

    <div class="ycbox4" v-if="ycbox4">
      <div class="ycbox4-title">
        <div></div>
        <div><span class="qianse">服务详情</span></div>
        <div @click="ycbox4 = !ycbox4">X</div>
      </div>
      <div v-if="items?.shopInfo?.services">
        <div v-for="(service, index) in items.shopInfo.services" :key="index">
          <p style="font-weight: 800">{{ service.name }}</p>
          <p>{{ service.desc }}</p>
          <div style="border-bottom: 1px solid #ccc"></div>
        </div>
      </div>
      <p v-else>品质加载中...</p>
    </div>

    <div class="zwbox"></div>

    <div class="jxsd" v-if="items?.rateLookInfo?.list">
      <p>精选晒单</p>
      <div class="tuijian">
        <div v-for="(item, index) in items.rateLookInfo.list" :key="index">
          <van-image width="85rem" height="85rem" fit="cover" :src="item.image" />
        </div>
      </div>
    </div>
    <div class="zwbox"></div>
    <div v-if="items?.rateInfo?.list">
      <div class="plpf">
        <div class="pl">评论({{ items.rateInfo.cRate }})</div>
        <div class="pf" @click="goToCommonRateList">
          评分<span>{{ items.rateInfoV2.cScore }}</span>
        </div>
      </div>
      <div class="pjbq">
        <div v-for="(item, index) in items.rateInfo.rateTags" :key="index">
          <div class="bq">{{ item.value }}({{ item.num }})</div>
        </div>
      </div>
      <div class="sypl">
        <div v-for="(item, index) in items.rateInfoV2.list" :key="index" class="us">
          <div class="userpl">
            <van-image round width="40rem" height="40rem" :src="item.user.avatar" />
            <div class="user">
              <div class="uname">{{ item.user.uname }}</div>
              <div class="ustyle">{{ item.style }}</div>
            </div>
          </div>
          <div class="content">{{ item.content }}</div>
        </div>
      </div>
    </div>
    <div class="zwbox"></div>

    <div class="shop" v-if="items?.shopInfo?.shopLabels">
      <img :src="items.shopInfo.shopLogo" alt="" />
      <div>
        <div class="shop-name">
          {{ items.shopInfo.name }}
        </div>
        <div class="shop-tj">
          推荐指数:
          {{ items.shopInfo.star }}
          |
          {{ items.shopInfo.saleDescV2 }}
        </div>

        <div class="shop-bq">
          <div v-for="(item, index) in items.shopInfo.shopLabels" :key="index">
            <div class="shop-qq">{{ item.text }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="zwbox"></div>


    <div class="dibudaoh">
      <van-action-bar>
        <van-action-bar-icon icon="shop-o" text="店铺" />
        <van-action-bar-icon icon="star-o" text="收藏" v-if="sckz" @click="sckz = !sckz" />
        <van-action-bar-icon
          icon="star-o"
          text="已收藏"
          color="red"
          v-if="!sckz"
          @click="sckz = !sckz"
        />
        <van-action-bar-button color="#ffecef" type="warning" text="加入购物车" @click="tianjgwc" />
        <van-action-bar-button color="#ff4466" type="danger" text="立即购买" @click="tiaozhuandd" />
      </van-action-bar>
    </div>

    <div class="box5">
      <div class="b51">商品详情</div>
      <div @click="ycbox5 = !ycbox5">商品参数</div>
    </div>
    <div class="detailInfo">
      <span>
        {{ items?.detailInfo?.desc || '抱歉！该商品暂无详情' }}
      </span>
    </div>

    <div class="ycbox5" v-if="ycbox5">
      <div class="ycbox4-title">
        <div></div>
        <div><span class="qianse">商品参数</span></div>
        <div @click="ycbox5 = false">X</div>
      </div>
      <div
        v-if="items?.itemParams?.info?.set"
        class="item-params"
        data-v-inspector="src/views/TiaoZhuan.vue:131:9"
      >
        <div
          v-for="([key, value], index) in Object.entries(items.itemParams.info.set)"
          :key="index"
          data-v-inspector="src/views/TiaoZhuan.vue:132:11"
        >
          <div class="b5xiaohz" data-v-inspector="src/views/TiaoZhuan.vue:133:11">
            <div class="b5x1" data-v-inspector="src/views/TiaoZhuan.vue:134:13">{{ key }}</div>
            <div class="b4x2" data-v-inspector="src/views/TiaoZhuan.vue:135:13">{{ value }}</div>
          </div>
        </div>
      </div>

      <p v-else>品质加载中...</p>
    </div>

    <!-- <p>
      当前商品id:
      {{ items?.promotionV2?.iid }}
    </p> -->

    <div class="gwc1" v-if="gwcxx">
      <div class="gwc8" @click="gwcxx = false">×</div>
      <div class="gwc5">

        <div class="gwc6"><img :src="items?.normalShareInfo?.imageUrl" alt="" /></div>

        <div class="gwc7">
          <div>
            ￥
            <span class="b2span">{{ items?.itemInfo?.highNowPrice || '加载中...' }}</span>
          </div>
          <div>已售：{{ items?.normalPrice?.sales || '加载中...' }}</div>
          <div>
            请选择 <span>{{ items?.skuBarInfo?.labelV2 }}</span>
          </div>

        </div>

      </div>

      <!-- 商品参数选择部分 -->

      <div v-if="items?.itemParams?.info?.set">
        <!-- 遍历 set 中的属性 -->
        <div v-for="(value, key) in items.itemParams.info.set" :key="key">
          <div class="gwc2" v-if="value.includes(',')">
            <p>{{ key }}</p>
            <div>
              <div class="gwc3">
                <div
                  v-for="(val, idx) in value.split(',')"
                  :key="idx"
                  :class="{
                    active: selectedAttributes[key] === val,
                    gaol: selectedAttributes[key] === val,
                  }"
                  @click="toggleAttributeSelection(key, val)"
                >
                  <div class="gwc4">{{ val }}</div>
                </div>
              </div>
            </div>
            <hr />
          </div>
        </div>
      </div>

      <p v-else>商品参数加载中...</p>

      <p>数量</p>
      <div style="margin-bottom: 60rem">
        <van-field name="stepper">
          <template #input>
            <van-stepper v-model="value" />
          </template>
        </van-field>
      </div>

      <div class="anniu" @click="addToCart">确定</div>
    </div>

    <div v-if="items?.detailInfo?.detailImage?.[0]?.list" class="image-gallery">
      <img
        v-for="(img, index) in items.detailInfo.detailImage[0].list"
        :key="index"
        :src="img"
        alt="商品图片"
        width="375rem"
      />
    </div>
    <p v-else>加载图片中...</p>

    <div class="dwanniu1">
      <van-icon name="wap-home-o" @click="goHome" />
    </div>

    <div class="dwanniu2">
      <van-icon name="cart-o" />
    </div>

    <div class="dwanniu1">
      <van-icon name="wap-home-o" @click="goHome" />
    </div>

    <div class="dwanniu2">
      <van-icon name="cart-o" @click="gosc" />
    </div>

    <div class="dwanniu3">
      <van-icon name="arrow-left" @click="goback"/>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { shangpxq } from '../api/index'
import { useGwcStore } from '../stores/gwc'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import { scgn } from '../stores/shouc'
import { Toast } from 'vant'
const router = useRouter()

const gwcStore = useGwcStore()

const items = ref<any | null>(null)
const activeIndex = ref(0)
const ycbox4 = ref(false)
const ycbox5 = ref(false)
const gwcxx = ref(false)
const value = ref(1)
const panduan = ref(false)
const sckz = ref(true)
const isLoading = ref(true)
const sc = scgn()

watch(
  () => sckz.value,
  (newValue) => {
    const scData = {
      id: items.value?.promotionV2?.iid, // 商品 ID
      name: items.value?.normalShareInfo?.title, // 商品名称
      price: items.value?.itemInfo?.highNowPrice, // 商品价格
      img: items.value?.normalShareInfo?.imageUrl, // 商品图片
      yis: items.value?.normalPrice?.sales, //售数量
    }

    if (!newValue) {
      // 收藏
      sc.addToFavorites(scData)
      Toast('已收藏')
    } else {
      // 取消收藏
      sc.removeFromFavorites(scData.id)
      Toast('取消收藏')
    }
  }
)

const goHome = () => {
  router.push('/')
}
const gosc = () => {
  router.push('/shoppingcar')
}
const goback = () => {
  router.go(-1)
}
// 存储购物车信息
const cartItems = ref<any[]>([])

const route = useRoute()
const receivedIid = ref<string | null>(null)
const tiaozhuandd = () => {
  gwcxx.value = true

  panduan.value = true
  console.log('跳转到订单页面', 'panduan', panduan.value)
}
const tianjgwc = () => {
  gwcxx.value = true

  panduan.value = false
  console.log('加入购物车', 'panduan', panduan.value)
}

watch(
  () => route.params.iid,
  (newIid) => {
    receivedIid.value = newIid
  },
  { immediate: true }
)
// 存储已点击的属性

onMounted(async () => {
  try {
    const response = await shangpxq(receivedIid.value)
    items.value = response.data.data.result
    console.log('商品详情:', items.value)
    isLoading.value = false
  } catch (error) {
    isLoading.value = false
    console.error('请求失败:', error)
  }
})

// 设置轮播图当前索引
const setActiveIndex = (index: number) => {
  activeIndex.value = index
}

const selectedAttributes = ref<{ [key: string]: string }>({})

// 点击属性时，高亮并记录选中的属性
const toggleAttributeSelection = (key: string, attribute: string) => {
  // 如果当前选中的属性与点击的属性相同，则取消高亮
  if (selectedAttributes.value[key] === attribute) {
    selectedAttributes.value[key] = '' // 取消选择
  } else {
    selectedAttributes.value[key] = attribute // 设置当前选中的属性
  }
}


// 点击“确定”按钮时，将商品信息添加到购物车数组
const addToCart = () => {
  const product = {
    id: items.value?.promotionV2?.iid, // 商品 ID
    title: items.value?.normalShareInfo?.title, // 商品名称
    price: items.value?.itemInfo?.highNowPrice, // 商品价格
    num: value.value, // 购买数量
    desc: selectedAttributes.value,
    thumb: items.value?.normalShareInfo?.imageUrl, // 商品图片
    storeName:items.value?.shopInfo.name//店铺
  };
  const cartItems = {
    id: items.value?.promotionV2?.iid, // 商品 ID
    title: items.value?.normalShareInfo?.title, // 商品名称
    price: items.value?.itemInfo?.highNowPrice, // 商品价格
    num: value.value, // 购买数量
    desc: selectedAttributes.value,
    thumb: items.value?.normalShareInfo?.imageUrl, // 商品图片
    storeName:items.value?.shopInfo.name//店铺
  };

 gwcStore.addProductToCart(product);

  // 关闭购物车选择框
  gwcxx.value = false;
  gwcxx.value = false;
  console.log('添加到购物车:', cartItems);
  if (panduan.value == false) {
    console.log(1);

    Toast('添加购物车成功');
  }
  else {
    console.log(22222222);
    console.log('cartItems:', cartItems);
    router.push({ name: 'orderCon', query: { cartItems:encodeURIComponent(JSON.stringify(cartItems) )} });

    console.log(JSON.stringify(cartItems));

  }
};
const goToCommonRateList = () => {
  const iid = items.value?.promotionV2?.iid;
console.log('iid', iid);

    router.push({ name: 'common-rate-list', query: { iid } });


};
</script>


<style scoped lang="less">
@import '../css/tiaozhuan.css';
.guanbi{
  position: absolute;
  top: 8rem;
  right: 8rem;
  font-size: 18rem;
}

.dwanniu3 {
  position: absolute;
  top: 10rem;
  left: 10rem;
  padding: 10rem;
  border-radius: 50%;
  background-color: #717070a1;
  color: #fff;
}

</style>
